package com.snail.billing.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.net.HttpApp;
import com.android.net.HttpResult;
import com.android.net.HttpSession;
import com.android.net.OnHttpResultListener;
import com.android.os.Page;
import com.android.util.AlertUtil;
import com.android.util.ResUtil;
import com.snail.billing.DataCache;
import com.snail.billing.PaymentParams;
import com.snail.billing.Resource;
import com.snail.billing.data.WorkDataManager;
import com.snail.billing.json.JsonArea;
import com.snail.billing.json.JsonBase;
import com.snail.billing.json.JsonWorkQuery;
import com.snail.billing.json.JsonWorkRecordLog;
import com.snail.billing.session.QueryAreaSession;
import com.snail.billing.session.WorkContinueAskSession;
import com.snail.billing.session.WorkRecordLogSession;
import com.snail.billing.session.WorkSaveSession;

public class WorkMoreFragment extends Page implements View.OnClickListener, OnHttpResultListener {

	private TextView textTitle;
	private View buttonBack;

	private View layout;
	private ListView listView;
	private EditText inputProblem;
	private View button;

	private List<Map<String, Object>> data;
	private SimpleAdapter adapter;

	private HttpApp httpApp;
	private QueryAreaSession queryAreaSession;
	private WorkSaveSession workSaveSession;
	private WorkRecordLogSession workRecordLogSession;
	private WorkContinueAskSession workContinueAskSession;
	private List<Map<String, Object>> data2;

	private String content;

	public static WorkParams workParams;

	@Override
	public int createLayoutId() {
		return ResUtil.getLayoutId(Resource.layout.snailbilling_work_more_activity);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		textTitle = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_text));
		textTitle.setText("我的提问");
		buttonBack = findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_button_back));
		buttonBack.setOnClickListener(this);
		//
		layout = findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_layout));
		layout.setVisibility(View.VISIBLE);
		listView = (ListView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_list_recode));
		inputProblem = (EditText) findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_input));
		button = findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_button));
		button.setOnClickListener(this);
		//
		setListViewData();
		int resource = ResUtil.getLayoutId(Resource.layout.snailbilling_work_more_item);
		String[] from = { MessageAdapter.MESSAGE };
		int[] to = { ResUtil.getViewId(Resource.id.snailbilling_work_more_text) };
		adapter = new MessageAdapter(getContext(), data, resource, from, to);
		listView.setAdapter(adapter);
	}

	@Override
	public void onResume() {
		super.onResume();
		httpApp = new HttpApp(getContext());
		if (!TextUtils.isEmpty(workParams.id)) {
			requestWorkRecordLog();
		}
	}

	@Override
	public void onClick(View v) {
		if (v.equals(buttonBack)) {
			getPageManager().backward();
			return;
		} else if (v.equals(button)) {
			content = inputProblem.getText().toString();
			if (TextUtils.isEmpty(content)) {
				AlertUtil.show(getContext(), "请输入问题");
				return;
			}
			if (workParams.isNew) {
				requestArea();
			} else if (!workParams.isFinish) {
				requestWorkContinue(content);
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put(MessageAdapter.MESSAGE, "此次提问已结束，如未解决请返回首页重新提问。谢谢！");
				map.put(MessageAdapter.IS_MINE, false);
				if (data2 == null) {
					data2 = new ArrayList<Map<String, Object>>();
				}
				data2.add(map);
				setListViewData();
				adapter.notifyDataSetChanged();
				listView.setSelection(listView.getCount() - 1);
			}
		}
	}

	private void requestWorkRecordLog() {
		workRecordLogSession = new WorkRecordLogSession(workParams.id);
		httpApp.setOnHttpResultListener(this);
		httpApp.request(workRecordLogSession);
	}

	private void requestArea() {
		httpApp.setDialogAutoDismiss(false);
		queryAreaSession = new QueryAreaSession();
		httpApp.setOnHttpResultListener(this);
		httpApp.request(queryAreaSession);
	}

	private void requestWorkSave(String content) {
		workSaveSession = new WorkSaveSession(workParams.parentCode, workParams.code, content);
		httpApp.setOnHttpResultListener(this);
		httpApp.request(workSaveSession);
		workParams.content = content;
	}

	private void requestWorkContinue(String content) {
		workContinueAskSession = new WorkContinueAskSession(workParams.id, content);
		httpApp.setOnHttpResultListener(this);
		httpApp.request(workContinueAskSession);
	}

	public void onHttpResult(HttpResult httpResult) {
		if (httpResult.isSucceed()) {
			HttpSession httpSession = httpResult.getHttpSession();
			if (httpSession.equals(workRecordLogSession)) {
				JsonWorkRecordLog jsonWorkRecordLog = new JsonWorkRecordLog((String) workRecordLogSession.getResponseData());
				if (jsonWorkRecordLog.getCode() == 1) {
					data2 = new ArrayList<Map<String, Object>>();
					for (int i = 0; i < jsonWorkRecordLog.getRecordLogs().size(); i++) {
						JsonWorkRecordLog.RecordLog recordLog = jsonWorkRecordLog.getRecordLogs().get(i);
						Map<String, Object> map = new HashMap<String, Object>();
						map.put(MessageAdapter.MESSAGE, recordLog.getContent());
						map.put(MessageAdapter.IS_MINE, recordLog.getType().equals("8") || recordLog.getType().equalsIgnoreCase("f"));
						data2.add(map);
					}
					setListViewData();
					adapter.notifyDataSetChanged();
					listView.setSelection(listView.getCount() - 1);
				} else {
					Toast.makeText(getContext(), jsonWorkRecordLog.getMessage(), Toast.LENGTH_SHORT).show();
				}
			} else if (httpSession.equals(queryAreaSession)) {
				JsonArea jsonArea = new JsonArea((String) queryAreaSession.getResponseData());
				if (jsonArea.getCode() == 1) {
					DataCache.getInstance().paymentParams = new PaymentParams();
					DataCache.getInstance().paymentParams.areaId = jsonArea.getAreaId();
					DataCache.getInstance().paymentParams.areaName = jsonArea.getAreaName();
					requestWorkSave(content);
				} else {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), jsonArea.getMessage(), Toast.LENGTH_SHORT).show();
				}
			} else if (httpSession.equals(workSaveSession)) {
				JsonBase jsonBase = new JsonBase((String) workSaveSession.getResponseData());
				if (jsonBase.getCode() == 1) {
					workParams.isNew = false;
					try {
						JSONObject json = new JSONObject((String) workSaveSession.getResponseData());
						if (json.has("workformId")) {
							workParams.id = json.getString("workformId");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					setListViewData();
					adapter.notifyDataSetChanged();
					listView.setSelection(listView.getCount() - 1);
					JsonWorkQuery.Problem problem = new JsonWorkQuery.Problem();
					problem.setId(workParams.id);
					problem.setState("1");
					problem.setTitle(workSaveSession.getTitle());
					problem.setContent(workSaveSession.getContent());
					problem.setCreateDate(workSaveSession.getCreateDate());
					WorkDataManager.getInstance().create(problem);
					inputProblem.setText("");
				} else {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), jsonBase.getMessage(), Toast.LENGTH_SHORT).show();
				}
			} else if (httpSession.equals(workContinueAskSession)) {
				JsonBase jsonBase = new JsonBase((String) workContinueAskSession.getResponseData());
				if (jsonBase.getCode() == 1) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put(MessageAdapter.MESSAGE, content);
					map.put(MessageAdapter.IS_MINE, true);
					if (data2 == null) {
						data2 = new ArrayList<Map<String, Object>>();
					}
					data2.add(map);
					setListViewData();
					adapter.notifyDataSetChanged();
					listView.setSelection(listView.getCount() - 1);
					inputProblem.setText("");
				} else {
					Toast.makeText(getContext(), jsonBase.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private void setListViewData() {
		if (data == null) {
			data = new ArrayList<Map<String, Object>>();
		}
		data.clear();
		Map<String, Object> map = null;
		map = new HashMap<String, Object>();
		map.put(MessageAdapter.MESSAGE, "欢迎使用蜗牛在线提问功能，请问有什么可以帮您吗？");
		map.put(MessageAdapter.IS_MINE, false);
		data.add(map);
		if (workParams.content != null) {
			map = new HashMap<String, Object>();
			map.put(MessageAdapter.MESSAGE, workParams.content);
			map.put(MessageAdapter.IS_MINE, true);
			data.add(map);
			map = new HashMap<String, Object>();
			map.put(MessageAdapter.MESSAGE, "请耐心等待,我们正在为您分配相关人员进行处理！");
			map.put(MessageAdapter.IS_MINE, false);
			data.add(map);
		}
		if (data2 != null) {
			for (int i = 0; i < data2.size(); i++) {
				data.add(data2.get(i));
			}
		}
	}

	private class MessageAdapter extends SimpleAdapter {

		private static final String MESSAGE = "message";
		private static final String IS_MINE = "is_mine";

		public MessageAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = super.getView(position, convertView, parent);
			View leftImage = convertView.findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_image_left));
			View leftImage2 = convertView.findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_image_left2));
			View rightImage = convertView.findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_image_right));
			View rightImage2 = convertView.findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_image_right2));
			TextView textView = (TextView) convertView.findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_more_text));
			if ((Boolean) data.get(position).get(IS_MINE)) {
				leftImage.setVisibility(View.GONE);
				leftImage2.setVisibility(View.GONE);
				rightImage.setVisibility(View.VISIBLE);
				rightImage2.setVisibility(View.VISIBLE);
				textView.setBackgroundColor(0xff27a5fe);
				textView.setTextColor(0xffffffff);
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
				layoutParams.leftMargin = 100;
				layoutParams.rightMargin = 0;
				textView.setLayoutParams(layoutParams);
			} else {
				leftImage.setVisibility(View.VISIBLE);
				leftImage2.setVisibility(View.VISIBLE);
				rightImage.setVisibility(View.GONE);
				rightImage2.setVisibility(View.GONE);
				textView.setBackgroundColor(0xfff1f1f1);
				textView.setTextColor(0xff000000);
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
				layoutParams.leftMargin = 0;
				layoutParams.rightMargin = 100;
				textView.setLayoutParams(layoutParams);
			}
			return convertView;
		}
	}

	public static class WorkParams {
		public boolean isNew;
		public String id;
		public String content;
		public String parentCode;
		public String code;
		public boolean isFinish;
	}
}
